package com.junjiao.util.java;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

/**
 * JSON操作类
 * 
 * @project 旅游 - 照片墙
 * @ClassName JSONUtil.java
 * @author jiaojun
 * @email junjiao.j@gmail.com
 * @version v1.0
 * @date 2012-3-20
 */
public class JSONUtil {

	/**
	 * 将json字符串转换成java bean
	 * 
	 * @param json
	 *            json字符串
	 * @param bean
	 *            要转换的java bean
	 * @return bean
	 */
	public static <T> T JSONToObject(Object o, Class<T> clz) {
		JSONObject jsonObject = JSONObject.fromObject(o);
		T t = (T) JSONObject.toBean(jsonObject, clz);
		return t;
	}

	/**
	 * 将json字符串转换成java bean
	 * 
	 * @param json
	 *            json字符串
	 * @param bean
	 *            要转换的java bean
	 * @return bean
	 */
	public static <T> List<T> JSONToListObject(List<?> list, Class<T> clz) {
		List<T> listObject = new ArrayList<T>();

		for (Object o : list) {
			T yp = JSONToObject(o, clz);
			listObject.add(yp);
		}
		return listObject;
	}
	
	public static Map getMap4Json(String jsonString){
		JSONObject jsonObject = JSONObject.fromObject( jsonString );  
		Iterator  keyIter = jsonObject.keys();
		String key;
		Object value;
		Map valueMap = new HashMap();
		while( keyIter.hasNext()){
			key = (String)keyIter.next();
			value = jsonObject.get(key);
			valueMap.put(key, value);
		}
		return valueMap;
	}

}
